<?php
    require_once('template.php'); //Require/include the template file
     
    if ($_GET['part'] == 5) {
        template_headtag('Install EightyThree - Step 5');
    } elseif ($_GET['part'] == 5) {
        template_headtag('Install EightyThree - Step 4');
    } elseif ($_GET['part'] == 2) {
        template_headtag('Install EightyThree - Step 2');
    } elseif ($_GET['part'] == 3) {
        template_headtag('Install EightyThree - Step 3');
    } else {
        template_headtag('Install EightyThree - Step 1');
    }
    template_header();
    template_left();
    echo "<div class='pageheadertext'>Install EightyThree</div>
        <br />";
     
    if (is_file('installed.php')) {
        errorbox("EightyThree is already installed!");
    } else {
        $installdir = getcwd();
         
        if ($_GET['part'] == 5) {
            if (!is_file('db.php')) {
                errorbox("db.php does not exist!");
                echo "<br />";
                echo "
                    <a href='install.php?part=3'>Retry</A>
                    ";
            } else {
                if (empty($_POST['username'])) {
                    errorbox ("Please enter a username!");
                    echo "<br />";
                    $error = TRUE;
                }
                if (empty($_POST['password'])) {
                    errorbox ("Please enter a password!");
                    echo "<br />";
                    $error = TRUE;
                }
                if ($_POST['password'] !== $_POST['confirmpassword']) {
                    errorbox ("Passwords do not match!");
                    echo "<br />";
                    $error = TRUE;
                }
                if (empty($_POST['email'])) {
                    errorbox ("Please enter an e-mail address!");
                    echo "<br />";
                    $error = TRUE;
                     
                } else {
                    if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email'])) {
                        errorbox ("Please enter a vaild e-mail address!");
                        echo "<br />";
                        $error = TRUE;
                    }
                }
                if ($error) {
                    echo "<br /><a href='javascript:history.back(1)'>Back</a>";
                } else {
                     
//Clean up vars to make sure they are safe to insert into the DB
                    $username = mysql_escape_string($_POST['username']);
                    $password = sha1($_POST['password']); //Encode the password with a sha1 hash
                    $firstname = mysql_escape_string($_POST['firstname']);
                    $lastname = mysql_escape_string($_POST['lastname']);
                    $email = mysql_escape_string($_POST['email']);
                     
                    include_once('db.php'); //Require/include the template file
                    $db = new my_db;
                    $db->query("SELECT * FROM login;");
                    if ($db->nf() > 0) {
                        errorbox("Login already exists!");
                        echo "<br />";
                    } elseif($db->nf() == 0) {
                        $db->query("INSERT INTO login (username, password, firstname, lastname, email, userlevel) VALUES('$username','$password','$firstname','$lastname', '$email', '3') ");
                         
                        echo "Admin login created!<br /><br />";
                    }
                     
                    $file_dirlist = '';
                    function recursive_list($directory) {
                        global $file_dirlist;
                         
                        if (is_dir($directory)) {
                            if ($dh = opendir($directory)) {
                                while (($file = readdir($dh)) !== false) {
                                     
                                    if ($file != "." && $file != ".." ) {
                                        if (is_dir("$directory/$file") ) {
                                            recursive_list("$directory/$file");
                                        } else {
                                            $file_dirlist .= "\$file[] = \"$directory/$file\"; \n \$filehash[] = \"".md5_file("$directory/$file")."\"; \n";
                                        }
                                    }
                                     
                                }
                                closedir($dh);
                            }
                        }
                        return $file_dirlist;
                    }
                    $installedcontents = "EightyThree";
                    $installedcontents .= recursive_list("$installdir");
                    $installedcontents .= "?>";
                    if (!is_writable($installdir) OR is_file('installed.php')) {
                        echo "Could not create installed.php. You can try creating the file manually with the following contents:<div style='font : Courier; border : #c3c3c3 solid 1px; overflow:auto; font-size : 12px; text-align : left; width:700px; height:300px;'>
                            ".nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($installedcontents)))."
                            </div>
                            <div class='installlink'><a href='index.php'>Next</a></div>
                            ";
                    } else {
                        $fh = fopen('installed.php', 'w') or die("can't open file");
                        fwrite($fh, $installedcontents);
                        fclose($fh);
                        echo "
                            <div class='subheadertext2'>Step 5 / 5</div>
                            <p>installed.php created!</p>
                            <br /><br />EightyThree is now installed!<br /><br />
                            <div class='installlink'><a href='index.php'>Next</a></div>
                            ";
                    }
                }
            }
        } elseif ($_GET['part'] == 4) {
            echo "
                <div class='subheadertext2'>Step 4 / 5</div>
                <form action='install.php?part=5' method='post'>
                <table class='table'>
                <tr>
                <td colspan='2' class='tabletitle'>
                EightyThree admin information
                </td>
                </tr>
                <tr>
                <td> First name: </td>
                <td> <input type='text' name='firstname' /> </td>
                </tr>
                <tr>
                <td> Last name: </td>
                <td> <input type='text' name='lastname' /> </td>
                </tr>
                <tr>
                <td> Username: </td>
                <td> <input type='text' name='username' /> </td>
                </tr>
                <tr>
                <td> Password: </td>
                <td> <input type='password' name='password' /> </td>
                </tr>
                <tr>
                <td>Confirm Password: </td>
                <td> <input type='password' name='confirmpassword' /> </td>
                </tr>
                <tr>
                <td> E-mail: </td>
                <td> <input type='text' name='email' /> </td>
                </tr>
                <tr>
                <td colspan='2'><input type='submit' value='Next' /></td>
                </tr>
                </table>
                </form>
                ";
        } elseif ($_GET['part'] == 3) {
            if (!is_file('db.php')) {
                errorbox("db.php does not exist!");
                echo "<br />";
                echo "
                    <a href='install.php?part=3'>Retry</A>
                    ";
            } else {
                include_once('db.php'); //Require/include the template file
                echo "<div class='subheadertext2'>Step 3 / 5</div>";
                
                $db = new my_db;
                 
                $db->query("SHOW TABLES like 'binarycontent';");
                if ($db->nf() > 0) {
                    errorbox("Binarycontent table already exists!");
                    echo "<br />";
                } elseif($db->nf() == 0) {
                    $db->query("CREATE TABLE `binarycontent` (
                        `dataid` char(32) NOT NULL default '',
                        `content` mediumblob,
                        `filetype` varchar(25) default NULL,
                        PRIMARY KEY  (`dataid`)
                        );");
                    echo "Binarycontent table created<br />";
                }
                $db->query("SHOW TABLES like 'content';");
                if ($db->nf() > 0) {
                    errorbox("Content table already exists!");
                    echo "<br />";
                } elseif($db->nf() == 0) {
                    $db->query("CREATE TABLE `content` (
                        `dataid` char(32) NOT NULL default '',
                        `content` text,
                        PRIMARY KEY  (`dataid`)
                        );");
                    echo "Content table created<br />";
                }
                $db->query("SHOW TABLES like 'trackedfiles';");
                if ($db->nf() > 0) {
                    errorbox("Trackedfiles table already exists!");
                    echo "<br />";
                } elseif($db->nf() == 0) {
                    $db->query("CREATE TABLE `trackedfiles` (
                        `id` int(11) NOT NULL auto_increment,
                        `filename` varchar(150) default NULL,
                        `filepath` varchar(255) default NULL,
                        `latestrev` varchar(32) default NULL,
                        `lastrevdate` datetime default NULL,
                        `lastuser` varchar(150) default NULL,
                        `filetype` varchar(25) default 'text/plain',
                        PRIMARY KEY  (`id`)
                        );");
                    echo "Trackedfiles table created<br />";
                }
                $db->query("SHOW TABLES like 'history';");
                if ($db->nf() > 0) {
                    errorbox("History table already exists!");
                    echo "<br />";
                } elseif($db->nf() == 0) {
                    $db->query("CREATE TABLE `history` (
                        `id` int(11) NOT NULL auto_increment,
                        `revhash` char(32) default NULL,
                        `filename` varchar(150) default NULL,
                        `filepath` varchar(255) default NULL,
                        `revdate` datetime default NULL,
                        `user` varchar(150) default NULL,
                        `revsummary` varchar(255) default NULL,
                        PRIMARY KEY  (`id`)
                        );");
                    echo "History table created<br />";
                }
                $db->query("SHOW TABLES like 'login';");
                if ($db->nf() > 0) {
                    errorbox("Login table already exists!");
                    echo "<br />";
                } elseif($db->nf() == 0) {
                    $db->query("CREATE TABLE `login` (
                        `id` int(11) NOT NULL auto_increment,
                        `username` varchar(30) NOT NULL default '',
                        `password` varchar(40) NOT NULL default '',
                        `firstname` varchar(30) default NULL,
                        `lastname` varchar(30) default NULL,
                        `email` varchar(30) default NULL,
                        `userlevel` varchar(10) default '0',
                        PRIMARY KEY  (`id`)
                        );");
                    echo "Login table created<br /><br /><br />";
                }
                echo "<div class='installlink'><a href='install.php?part=4'>Next</a></div>
                    ";
            }
             
        } elseif ($_GET['part'] == 2) {
            $dbcontents = "<?php
                ";
            switch ($_POST['dbtype']) {
                case 'MySQL':
                $dbcontents .= "
//Database Information
\$db_type = \"mysql\"; //Database type
                     
//include the files needed to deal with the db type selected above
require_once (\"classes/phplib/db_\".\$db_type.\".inc\");
require_once (\"classes/phplib/ct_sql.inc\");
                    ";
                break;
                case 'PostgreSQL':
                $dbcontents .= "
//Database Information
\$db_type = \"pgsql\"; //Database type
                     
//include the files needed to deal with the db type selected above
require_once (\"classes/phplib/db_\".\$db_type.\".inc\");
require_once (\"classes/phplib/ct_sql.inc\");
                    ";
                break;
                case 'mSQL':
                $dbcontents .= "
//Database Information
\$db_type = \"msql\"; //Database type
                     
//include the files needed to deal with the db type selected above
require_once (\"classes/phplib/db_\".\$db_type.\".inc\");
require_once (\"classes/phplib/ct_sql.inc\");
                    ";
                break;
                case 'Sybase':
                $dbcontents .= "
//Database Information
\$db_type = \"sybase\"; //Database type
                     
//include the files needed to deal with the db type selected above
require_once (\"classes/phplib/db_\".\$db_type.\".inc\");
require_once (\"classes/phplib/ct_sql.inc\");
                    ";
                break;
                case 'Microsoft SQL Server':
                $dbcontents .= "
//Database Information
\$db_type = \"mssql\"; //Database type
                     
//include the files needed to deal with the db type selected above
require_once (\"classes/phplib/db_\".\$db_type.\".inc\");
require_once (\"classes/phplib/ct_sql.inc\");
                    ";
                break;
                case 'ODBC':
                $dbcontents .= "
//Database Information
\$db_type = \"odbc\"; //Database type
                     
//include the files needed to deal with the db type selected above
require_once (\"classes/phplib/db_\".\$db_type.\".inc\");
require_once (\"classes/phplib/ct_sql.inc\");
                    ";
                break;
                case 'Oracle':
                $dbcontents .= "
//Database Information
\$db_type = \"oracle\"; //Database type
                     
//include the files needed to deal with the db type selected above
require_once (\"classes/phplib/db_\".\$db_type.\".inc\");
require_once (\"classes/phplib/ct_sql.inc\");
                    ";
                break;
            }
            $dbcontents .= "
class my_db extends DB_Sql {
var \$Host = \"".mysql_escape_string($_POST['dbhost'])."\"; //Database hostname (most likely localhost)
var \$Database = \"".mysql_escape_string($_POST['dbname'])."\"; //Database name
var \$User = \"".mysql_escape_string($_POST['dbuser'])."\"; //Database user uesrname
var \$Password = \"".mysql_escape_string($_POST['dbpassword'])."\"; //Database user passowrd
}
?>";
            if (!is_writable($installdir) OR is_file('db.php')) {
                echo "Could not create db.php. You can try creating the file manually with the following contents:<div style='font : Courier; border : #c3c3c3 solid 1px; overflow:auto; font-size : 12px; text-align : left; width:700px; height:300px;'>
                    ".nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($dbcontents)))."
                    </div>
                    <div class='installlink'><a href='install.php?part=3'>Next</a></div>
                    ";
            } else {
                $fh = fopen('db.php', 'w') or die("can't open file");
                fwrite($fh, $dbcontents);
                fclose($fh);
                echo "
                    <div class='subheadertext2'>Step 2 / 5</div>
                    <p>db.php created!</p>
                    <br />
                    <br />
                    <div class='installlink'><a href='install.php?part=3'>Next</a></div>
                     
                    ";
            }
             
            echo "$dbcontents";
        } else {
            if (!is_writable($installdir)) {
                errorbox("$installdir<br /> is not writable!
                    <br /><span style='font : italic 14px serif;'>In order to create db.php, the install directory must be writable</span>", '400px');
                echo "<br />";
                 
            }
            if (is_file('db.php')) {
                errorbox("db.php already exists!");
                echo "<br />";
            }
            if (ini_get('register_globals')) {
                errorbox("Please turn register_globals off!");
                echo "<br />";
            }
            echo "
                <div class='subheadertext2'>Step 1 / 5</div>
                <form action='install.php?part=2' method='post'>
                <table class='table'>
                <tr>
                <td colspan='2' class='tabletitle'>
                Database information
                </td>
                </tr>
                <tr>
                <td>Database type:</td>
                <td>
                <select name='dbtype'>
                <option>MySQL</option>
                <option>PostgreSQL</option>
                <option>mSQL</option>
                <option>Sybase</option>
                <option>Microsoft SQL Server</option>
                <option>ODBC</option>
                <option>Oracle</option>
                <option>Disabled</option>
                </select>
                </td>
                </tr>
                <tr>
                <td>Database hostname:</td>
                <td><input type='text' name='dbhost' value='localhost' /></td>
                </tr>
                <tr>
                <td>Database name:</td>
                <td><input type='text' name='dbname' value='EightyThree' /></td>
                </tr>
                <tr>
                <td>Database user username:</td>
                <td><input type='text' name='dbuser' value='83_user' /></td>
                </tr>
                <tr>
                <td>Database user password:</td>
                <td><input type='password' name='dbpassword' /></td>
                </tr>
                <td colspan='2'><input type='submit' value='Next' /></td>
                </tr>
                </table>
                </form>
                ";
        }
    }
    echo "";
    template_footer();
?>
